package com.atguigu.study.config;


import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @author Marco
 * @date 2025/8/21 13:57
 * @email 3293336923@qq.com
 * @Description 知识出处： https://docs.langchain4j.dev/tutorials/chat-memory/#persistence
 */
@Component
public class RedisChatMemoryStore implements ChatMemoryStore {


    private static final String CHAT_MEMORY_PREFIX = "CHAT_MEMORY";

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public List<ChatMessage> getMessages(Object memoryId) {

        String retValue = redisTemplate.opsForValue().get(CHAT_MEMORY_PREFIX + memoryId);
//        将 json 进行 反序列化
        return ChatMessageDeserializer.messagesFromJson(retValue);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        redisTemplate.opsForValue().set(CHAT_MEMORY_PREFIX + memoryId,
//         将 传递 进来的 消息 序列化，存储在 Redis 中
                ChatMessageSerializer.messagesToJson(messages)
        );
    }

    @Override
    public void deleteMessages(Object memoryId) {
        redisTemplate.delete(CHAT_MEMORY_PREFIX + memoryId);
    }
}
